package com.charley.icloud.security.utils;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 密码工具类
 */
public class PasswordUtils {

	/**
	 * 匹配密码
	 * @param salt 盐
	 * @param rawPass 明文
	 * @param encPass 密文
	 * @return true 匹配成功
	 */
	public static boolean matches(String salt, String rawPass, String encPass) {
		return new PasswordEncoder(salt).matches(encPass, rawPass);
	}

	/**
	 * 明文密码加密
	 * @param rawPass 明文
	 * @param salt 盐
	 * @return 密文
	 */
	public static String encode(String rawPass, String salt) {
		return new PasswordEncoder(salt).encode(rawPass);
	}

	/**
	 * UUID 模式 获取加密盐
	 * @return 盐
	 */
	public static String getSaltByUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);
	}

	public static String getSalt() {
		return SaltGenerator.generateSalt();
	}

	public static String getSalt(Integer length){
		return SaltGenerator.generateSalt(length);

	}
	/**
	 * 加密盐随机生成器
	 * */
	private static class SaltGenerator {

		// 盐 长度
		private final static Integer SLAT_LENGTH = 20;

		public static String generateSalt(){
			return SaltGenerator.generateSalt(SaltGenerator.SLAT_LENGTH);
		}

		public static String generateSalt(int length) {
			SecureRandom random = new SecureRandom();
			byte[] salt = new byte[length];
			random.nextBytes(salt);
			return bytesToHex(salt);
		}

		// 将字节数组转换为十六进制字符串
		private static String bytesToHex(byte[] bytes) {
			StringBuilder hex = new StringBuilder();
			for (byte b : bytes) {
				hex.append(String.format("%02X", b));
			}
			return hex.toString();
		}
	}
}
